//
//  CustomHeader.m
//  MexicoLoan
//
//  Created by wxp on 2025/2/25.
//

#import "CustomHeader.h"

@interface CustomHeader()

@property (nonatomic, strong) UIImageView * loadingImageView;

@end

@implementation CustomHeader

- (void)prepare{
    [super prepare];
    self.stateLabel.hidden = YES;
    self.lastUpdatedTimeLabel.hidden = YES;
    
    self.loadingImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon-refresh-image"]];
    self.loadingImageView.center = CGPointMake(self.mj_w / 2, self.mj_h / 2);
    self.loadingImageView.centerX = SCREEN_WIDTH/2;
    [self addSubview:self.loadingImageView];
    [self setRotationAnimationForImageView:self.loadingImageView];
}

- (void)setState:(MJRefreshState)state {
    [super setState:state];
    // 根据状态控制动画
    switch (state) {
        case MJRefreshStateIdle:
        case MJRefreshStateRefreshing: {
            // 开始动画
            [self startLoadingAnimation];
            break;
        }
        default:
            break;
    }
}

- (void)startLoadingAnimation {
    // 移除可能存在的旧动画
    [self.loadingImageView.layer removeAnimationForKey:@"rotationAnimation"];
    
    // 添加新动画
    CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    rotationAnimation.fromValue = @(0);
    rotationAnimation.toValue = @(M_PI * 2);
    rotationAnimation.duration = 1.0;
    rotationAnimation.repeatCount = HUGE_VALF;
    rotationAnimation.removedOnCompletion = NO;
    [self.loadingImageView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}

- (void)setRotationAnimationForImageView:(UIImageView *)imageView {
    CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    rotationAnimation.fromValue = @(0);
    rotationAnimation.toValue = @(M_PI * 2);
    rotationAnimation.duration = 1.0;
    rotationAnimation.repeatCount = HUGE_VALF;
    [imageView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}

@end
